package com.ehualu.esresult;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ehualu.esresult.utils.ESurlUtil;
import com.ehualu.esresult.utils.HttpUtil;
import com.ehualu.esresult.utils.LoadProperties;
import com.ehualu.esresult.utils.MysqlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: 吴敬超
 * @Date: 2020/7/16 17:33
 */
public class RuningTimes {

    private static final Logger LOG = LoggerFactory.getLogger(RuningTimes.class);

    public static void main(String[] args) {

        while (true) {

            LOG.info("*******************循环执行函数*************************");

            runing();

            try {
                /*一小时执行一次*/
                /*24 * 60 * 60 * 1000;*/
                Thread.sleep(24 * 60 * 60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

    public static void runing() {

        LoadProperties loadProc = LoadProperties.getInstance();

//        String postjosn = loadProc.getValues("search.automatic_s", "");

        String postjosn = loadProc.getValues("search.automatic_s.time", "");


        String posturl = ESurlUtil.getUrl("index.vehicle");
        if (posturl.equals("")) {
            LOG.info("posturl 是空，不继续执行");


            return;
        }


        String result = HttpUtil.HttpPostWithJson(posturl, postjosn);


        if (result.equals("DefaultReturnValue")) {

            LOG.info("ES请求结果是空，不继续执行");
            return;

        }
//        LOG.info("ES请求结果是:" + result);


        JSONArray jsonArray = JSON.parseObject(result)
                .getJSONObject("aggregations")
                .getJSONObject("group_by_automatic_s")
                .getJSONArray("buckets");

        MysqlUtil mysqlUtil = new MysqlUtil();

        /*遍历桶*/
        for (int i = 0; i < jsonArray.size(); i++) {

            JSONObject buckets = jsonArray.getJSONObject(i);


            String key = buckets
                    .getString("key");

            String buckets_count = buckets
                    .getJSONObject("sales_over_time_count")
                    .getString("count");


            LOG.info("key is :" + key);

            LOG.info("buckets_count is :" + buckets_count);
            mysqlUtil.updateRuntimes(key, buckets_count);


        }


    }
}
